package com.example.demo;

import com.alibaba.fastjson2.JSONObject;
import com.example.demo.simple.service.RedisSearchService;
import com.example.demo.stream.common.DataObject;
import com.example.demo.stream.common.enums.DataType;
import com.example.demo.stream.common.enums.OptType;
import com.example.demo.stream.producer.StreamMessageProducer;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/stream")
public class StreamTestController {

    @Autowired
    private RedisSearchService searchService;

    private final StreamMessageProducer producer;

    public StreamTestController(StreamMessageProducer producer) {
        this.producer = producer;
    }

    @PostMapping("/send")
    public String send(@RequestParam String tipic,
                       @RequestParam String content) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", content);
        DataObject<String> obj = DataObject.<String>builder()
                .dataType(DataType.PRODUCT)
                .optType(OptType.ADD)
                .primaryKey("p123")
                .data(jsonObject.toJSONString())
                .build();

        producer.send(tipic, obj);
        return "发送成功";
    }

    @GetMapping("testSave")
    public String testSave() throws JsonProcessingException {
        for (int i=0;i<=10000;i++){
            Map<String, String> productFields1 = new HashMap<>();
            productFields1 = new HashMap<>();
            productFields1.put("name", "苹果电子手机"+i);
            productFields1.put("category", "电子"+i);
            productFields1.put("description", "旗舰机型"+i);
            searchService.save("product1", 300L+i, productFields1);
        }
        return "success";
    }
}
